package com.school.gmz.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.gmz.common.Result;
import com.school.gmz.entity.Course;
import com.school.gmz.mapper.CourseMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/course")
@Api(tags = "课程管理") // 定义API的分类
public class CourseController {
    @Resource
    CourseMapper courseMapper;

    // 添加课程
    @PostMapping
    @ApiOperation(value = "添加课程", notes = "创建一个新的课程记录")
    public Result<?> save(@RequestBody Course course){
        courseMapper.insert(course);
        return Result.success();
    }

    // 更新课程
    @PutMapping
    @ApiOperation(value = "更新课程", notes = "根据ID更新课程记录")
    public Result<?> update(@RequestBody Course course){
        courseMapper.updateById(course);
        return Result.success();
    }

    // 删除课程
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除课程", notes = "根据ID删除课程记录")
    public Result<?> delete(@ApiParam(value = "课程ID", required = true) @PathVariable Long id){
        courseMapper.deleteById(id);
        return Result.success();
    }

    // 查询课程
    @GetMapping
    @ApiOperation(value = "查询课程", notes = "支持关键字搜索和教室搜索")
    public Result<?> findPage(
            @ApiParam(value = "搜索关键字", defaultValue = "") @RequestParam(defaultValue = "") String course,
            @ApiParam(value = "教室", defaultValue = "") @RequestParam(defaultValue = "") String classroom){
        LambdaQueryWrapper<Course> wrapper = Wrappers.<Course>lambdaQuery();
        if (StrUtil.isNotBlank(course)){
            wrapper.like(Course::getCourse, course);
        }
        if (StrUtil.isNotBlank(classroom)){
            wrapper.like(Course::getClassroom, classroom);
        }
        Page<Course> coursePage = courseMapper.selectPage(new Page<>(1, 10), wrapper); // 默认分页参数
        return Result.success(coursePage);
    }
}